<?php


namespace App\Services;


use App\Models\SmsCode;
use App\Services\ChuanglanSMS\ApiService as SmsService;
use Illuminate\Support\Facades\DB;

class Sms
{
    public function send($phone)
    {
        $shopId = empty($_SERVER['HTTP_SHOP_ID']) ? null : $_SERVER['HTTP_SHOP_ID'];
        $shopInfo = DB::table('pos_core.store')
            ->where('id', '=', $shopId)
            ->first();
        if (empty($shopInfo) || empty($shopInfo->sms_header))
            return ['error' => true, 'message' => '该门店未配置短信签名，请联系管理员进行配置~'];

        $smsHeader = $shopInfo->sms_header;
        $msg = '【' . $smsHeader . '】您的会员验证码是{$var}，该验证码{$var}分钟内有效，请勿将验证码泄露给他人，如非本人操作，请忽略短信。';
        $code = mt_rand(100000, 999999);
        $params = "{$phone},{$code},10";

        $smsService = new SmsService();
        $result = $smsService->sendVariableSMS($msg, $params);

        if (!is_null(json_decode($result))) {

            $output = json_decode($result, true);

            if (isset($output['code']) && $output['code'] == '0') {
                $model = new SmsCode();
                $data = [
                    'phone' => $phone,
                    'code' => $code
                ];
                $insert = $model->insert($data);
                if (empty($insert)) {
                    return ['error' => true, 'message' => '验证码记录失败，请稍后再试~'];
                }
                return ['error' => false];
            } else {
                return ['error' => true, 'message' => $output['errorMsg']];
            }
        } else {
            return ['error' => true, 'message' => '发送失败，请稍后再试~'];
        }
    }

    public function checkCode($phone, $code)
    {
        $model = new SmsCode();
        $codeInfo = $model
            ->where('phone', '=', $phone)
            ->where('code', '=', $code)
            ->where('status', '=', 0)
            ->orderBy('created_at')
            ->first();
        if (empty($codeInfo)) {
            return ['error' => true, 'message' => '验证失败', 'code' => 110023];
        }

        if (strtotime($codeInfo->created_at) < (time() - 600)) {
            return ['error' => true, 'message' => '验证码无效', 'code' => 110022];
        }
        $result = $model->where('id', '=', $codeInfo->id)->update(['status' => 1]);
        if (empty($result))
            return ['error' => true, 'message' => '验证失败，请稍后重试~'];
        return ['error' => false];
    }
}